import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/user'
import { routes } from './static'
import { useConfigStore } from '@/stores/syscfg'
const loadView = import.meta.glob('@/views/**/*.vue')
import { ref } from 'vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
const routeRegFlag = ref(false) // 定义标识，记录路由是否添加

// 权限拦截
router.beforeEach((to, from, next) => {
  const config = useConfigStore()
  const store = useAuthStore()
  const isAuth = store.user.isAuthenticated
  const permission = store.user.permission
  if (!routeRegFlag.value) {
    addR(config.cfg.routes, 'Manage')
    routeRegFlag.value = true
    if (isAuth)
      next({
        path: `${to.path}`
      })
    else
      router.replace({
        name: 'Login'
      })
  }
  if (!to.meta.skipFilter) {
    if (to.meta.permission && permission.indexOf(to.meta.permission) != -1) {
      if (isAuth) next()
      else
        return router.replace({
          name: 'Login'
        })
    } else {
      if (isAuth)
        return router.replace({
          name: 'notPermit'
        })
      else
        return router.replace({
          name: 'Login'
        })
    }
  } else next()
})
export { routes, router }
export default router
export function addRoute() {
  const store = useConfigStore()
  const e = store.cfg.routes
  addR(e, 'Manage')
  router.push({ name: 'Home' })
}
function addR(menu, pManu) {
  menu.forEach((e) => {
    if (!e.children || e.children.length === 0) {
      router.addRoute(pManu, {
        name: e.name,
        path: e.path,
        meta: e.meta,
        component: loadView[`/src/views${e.componentPath}.vue`]
      })
    } else {
      router.addRoute(pManu, {
        name: e.name,
        path: e.path,
        meta: e.meta
      })
      addR(e.children, e.name)
    }
  })
}
